package com.mzkj.wanjulaile.mobile.api.modules.order.service;

import com.mzkj.common.utils.Collections3;
import com.mzkj.common.utils.StringUtils;
import com.mzkj.wanjulaile.mobile.api.modules.brand.mapper.BrandMapper;
import com.mzkj.wanjulaile.mobile.api.modules.order.entity.OrderToy;
import com.mzkj.wanjulaile.mobile.api.modules.order.mapper.OrderToyMapper;
import com.mzkj.wanjulaile.mobile.api.modules.toy.entity.Image;
import com.mzkj.wanjulaile.mobile.api.modules.toy.entity.Toy;
import com.mzkj.wanjulaile.mobile.api.modules.toy.mapper.ImageMapper;
import com.mzkj.wanjulaile.mobile.api.modules.toy.mapper.ToyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(readOnly = true)
public class OrderToyServiceImpl  implements OrderToyService {
	@Autowired
	private OrderToyMapper orderToyMapper;
	@Autowired
	private ImageMapper imageMapper;

	@Autowired
	private ToyMapper toyMapper;
	@Autowired
	private BrandMapper brandMapper;

	public OrderToy get(String id) {
		return orderToyMapper.get(id);
	}
	
	public List<OrderToy> findList(OrderToy orderToy) {
		return orderToyMapper.findList(orderToy);
	}
	
	@Transactional(readOnly = false)
	public void save(OrderToy orderToy) {

	}
	
	@Transactional(readOnly = false)
	public void delete(OrderToy orderToy) {
		orderToyMapper.delete(orderToy);
	}

	public List<OrderToy> getListByOrderId(String orderId){
		List<OrderToy> orderToys = orderToyMapper.getListByOrderId(orderId);
		if (orderToys != null){
			for (OrderToy temp : orderToys){
				setImagesAndParts(temp);
			}
		}
		return orderToys;
	}

	 public void setImagesAndParts(OrderToy temp) {
		Toy toy = temp.getToy();
		toy = toyMapper.get(toy);
		Image image = new Image();
//		ToyPart toyPart = new ToyPart();
		image.setToy(toy);
//		toyPart.setToy(toy);
		toy.setImages(imageMapper.getListByToyId(image));
//		toy.setToyParts(toyPartDao.getPartByToyId(toyPart));
		toy.setBrand(brandMapper.get(toy.getBrand()));
		temp.setToy(toy);
	}


	@Transactional(readOnly = false)
	public void update(OrderToy orderToy) {
		if (StringUtils.isBlank(orderToy.getId())){
			orderToy.setIsNewRecord(true);
			orderToy.preInsert();
			orderToyMapper.insert(orderToy);
		}else{
			orderToy.preUpdate();
			orderToyMapper.update(orderToy);
		}
	}

	/**
	 * 查询上一次订单中的玩具
	 * @param orderId
	 * @return
     */
	public List<Toy> getToyListToyByOrderId(String orderId) {
		List<Toy> toyList = orderToyMapper.getToyListToyByOrderId(orderId);
		if(!Collections3.isEmpty(toyList)){
			for (Toy toy :toyList){
				setImage(toy);
			}
		}
		return toyList;
	}

	 public void setImage(Toy toy) {
		Image image = new Image();
		image.setToy(toy);
		toy.setImages(imageMapper.getListByToyId(image));
	}
}